package com.tianji.learning.service.impl;

import com.tianji.api.client.user.UserClient;
import com.tianji.api.dto.user.UserDTO;
import com.tianji.common.exceptions.BizIllegalException;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.StringUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.constants.RedisConstants;
import com.tianji.learning.domain.po.PointsBoard;
import com.tianji.learning.domain.query.PointsBoardQuery;
import com.tianji.learning.domain.vo.PointsBoardItemVO;
import com.tianji.learning.domain.vo.PointsBoardVO;
import com.tianji.learning.mapper.PointsBoardMapper;
import com.tianji.learning.service.IPointsBoardService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 学霸天梯榜 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-01-27
 */
@Service
@RequiredArgsConstructor
public class PointsBoardServiceImpl extends ServiceImpl<PointsBoardMapper, PointsBoard> implements IPointsBoardService {

    private final StringRedisTemplate redisTemplate;

    private final UserClient userClient;

    /**
     * 分页查询指定赛季的积分排行榜
     * @param query
     * @return
     */
    @Override
    public PointsBoardVO queryPointsBoardBySeason(PointsBoardQuery query) {
        //1.获取当前用户id
        Long userId = UserContext.getUser();

        //2.判断是查当前赛季还是历史赛季  query.season  赛季id，为null或者0则代表查询当前赛季
        boolean isCurrent = query.getSeason()==null || query.getSeason()==0; //该字段为 true则查当前赛季 redis
        //获取Redis的Key
        LocalDateTime now = LocalDateTime.now();
        String format = now.format(DateTimeFormatter.ofPattern("yyyyMM"));
        String key = RedisConstants.POINTS_BOARD_KEY_PREFIX + format;

        Long season = query.getSeason(); //历史赛季id

        //3.查询我的排名和积分  query.season 判断是否查redis还是db
        PointsBoard myBoard = isCurrent ?
                queryMyCurrentBoard(key) : // 查询当前榜单（Redis）
                queryMyHistoryBoard(season); // 查询历史榜单（MySQL）

        //4.分页查询赛季列表  判断是否查redis还是db
        List<PointsBoard> list = isCurrent ?
                queryCurrentBoardList(key, query.getPageNo(), query.getPageSize()) :
                queryHistoryBoardList(query);

        //封装用户id集合 远程调用用户服务 获取用户信息 list转map
        Set<Long> uids = list.stream().map(PointsBoard::getUserId).collect(Collectors.toSet());
        List<UserDTO> userDTOS = userClient.queryUserByIds(uids);
        if (CollUtils.isEmpty(userDTOS)){
            throw new BizIllegalException("用户不存在");
        }
        //转map key：用户id  value：用户名称
        Map<Long, String> userDtoMap = userDTOS.stream().collect(Collectors.toMap(UserDTO::getId, c -> c.getName()));

        //5.封装vo返回
        PointsBoardVO vo = new PointsBoardVO();
        vo.setRank(myBoard.getRank()); //我的排名
        vo.setPoints(myBoard.getPoints()); //我的积分

        List<PointsBoardItemVO> voList = new ArrayList<>();
        for (PointsBoard pointsBoard : list) {
            PointsBoardItemVO itemVO = new PointsBoardItemVO();
            pointsBoard.getUserId();
            itemVO.setName(userDtoMap.get(pointsBoard.getUserId()));
            itemVO.setPoints(pointsBoard.getPoints());
            itemVO.setRank(pointsBoard.getRank());
            voList.add(itemVO);
        }

        vo.setBoardList(voList);
        return vo;
    }

    /**
     * 查询历史赛季排行榜列表
     * @param query
     * @return
     */
    private List<PointsBoard> queryHistoryBoardList(PointsBoardQuery query) {
        //todo
        return null;
    }

    /**
     * 查询当前赛季排行榜列表 redis zset
     * @param key
     * @param pageNo 页码
     * @param pageSize 条数
     * @return
     */
    public List<PointsBoard> queryCurrentBoardList(String key, Integer pageNo, Integer pageSize) {
        //1.计算start 和 stop 分页值
        int start = (pageNo - 1) * pageSize;
        int end = start + pageSize -1;

        //2.利用zrevrange名 会按分数倒叙 分页查询
        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisTemplate.opsForZSet().reverseRangeWithScores(key, start, end);
        if (CollUtils.isEmpty(typedTuples)){
            return CollUtils.emptyList();
        }
        //3.封装结果返回
        int rank = start + 1;
        ArrayList<PointsBoard> list = new ArrayList<>();
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            String value = typedTuple.getValue(); //用户id
            Double score = typedTuple.getScore(); //总积分值
            if (StringUtils.isBlank(value) || score == null){
                continue;
            }
            PointsBoard board = new PointsBoard();
            board.setUserId(Long.valueOf(value));
            board.setPoints(score.intValue());
            board.setRank(rank++);
            list.add(board);
        }
        return list;
    }

    //查询历史赛季 我的积分和排名 db
    private PointsBoard queryMyHistoryBoard(Long season) {
        //todo
        return null;
    }

    //查询当前赛季 我的积分和排名 redis
    private PointsBoard queryMyCurrentBoard(String key) {
        //1.获取当前用户信息
        String userId = UserContext.getUser().toString();
        //获取分值
        Double score = redisTemplate.opsForZSet().score(key, userId.toString());
        //获取排名
        Long rank = redisTemplate.opsForZSet().reverseRank(key, userId.toString());

        PointsBoard board = new PointsBoard();
        board.setRank(rank == null ? 0 : rank.intValue() + 1);
        board.setPoints(score == null ? 0 : score.intValue());
        return board;
    }
}